package org.geoscrape.util;

/**
 * Useful stuff.
 */
public class Tools
{
	// Supported languages:
	// English,Norsk,Deutsch,Polski,Français,Svenska,Español,Português,Čeština,Nederlands,Català,Eesti,Magyar,Română,Korean

	private static final String[] YESTERDAY = new String[] { "yesterday", "wczoraj", "i går", "igår", "gestern",
			"hier", "ayer", "ontem", "včera", "gisteren", "ahir", "eile", "tegnap", "ieri", "어제" };
	private static final String[] TODAY = new String[] { "today", "dzisiaj", "i dag", "idag", "heute", "aujourd'hui",
			"hoy", "hoje", "dnes", "vandaag", "avui", "täna", "ma", "azi", "오늘" };

	/**
	 * Sleep for the indicated number of milliseconds. Ignores
	 * InterruptedException.
	 * 
	 * @param millis
	 */
	public static void sleep(long millis)
	{
		try
		{
			Thread.sleep(millis);
		}
		catch (InterruptedException e)
		{
			// ignored
		}
	}

	/**
	 * Return true if time represents "today" in any of the supported languages.
	 * 
	 * @param time
	 * @return
	 */
	public static boolean isToday(String time)
	{
		return contains(TODAY, time.toLowerCase());
	}

	/**
	 * Return true if time represents "yesterday" in any of the supported
	 * languages.
	 * 
	 * @param time
	 * @return
	 */
	public static boolean isYesterday(String time)
	{
		return contains(YESTERDAY, time.toLowerCase());
	}

	/**
	 * Checks if the string word is in an array of strings.
	 * 
	 * @param words
	 * @param word
	 * @return
	 */
	private static boolean contains(String[] words, String word)
	{
		for (String w : words)
		{
			if (w.equals(word))
			{
				return true;
			}
		}
		return false;
	}

	/**
	 * Performs ROT-13 encryption/decryption on any character not in a html tag.
	 * 
	 * @param input
	 * @return
	 */
	public static String rot13(String input)
	{
		String output = "";
		boolean doDecode = true;
		for (int x = 0; x < input.length(); x++)
		{
			int c = input.codePointAt(x);
			if (c == (int) '[' || c == (int) '<')
			{
				// turn off when we reach a bracket
				doDecode = false;
			}
			else if (c == (int) ']' || c == (int) '>')
			{
				// turn on when we reach an end bracket
				doDecode = true;
			}
			if (doDecode)
			{
				if ((c >= 'A' && c <= 'M') || (c >= 'a' && c <= 'm'))
				{
					c += 13;
				}
				else if ((c >= 'N' && c <= 'Z') || (c >= 'n' && c <= 'z'))
				{
					c -= 13;
				}
			}
			output+=(char)c;
		}
		return output;
	}
}
